package org.arch_learn.orm_starter.utils;

import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

public class ScanUtils {
    private static Set<String> xmlPaths = new HashSet<String>();

    private static Set<String> mapperNames = new HashSet<>();

    public static void doScanXmls(String rootPath) throws IOException {
        String scanPackagePath = Thread.currentThread().getContextClassLoader()
                .getResource("").getPath() + rootPath.replaceAll("\\.", "/");

        File file = new File(scanPackagePath);
        File[] files = file.listFiles();
        for (File f : files) {
            if (f.isDirectory()) {
                doScanXmls(rootPath + "." + f.getName());
            } else if (f.getName().endsWith(".xml")) {
                String pathPrefix = rootPath.replaceAll("\\.", "/");
                String mapperXmlPath = pathPrefix + "/" + f.getName();
                xmlPaths.add(mapperXmlPath);
            }
        }
    }

    public static void doScanMappers(String rootPath) throws IOException {
        String scanPackagePath = Thread.currentThread().getContextClassLoader()
                .getResource("").getPath() + rootPath.replaceAll("\\.", "/");

        File file = new File(scanPackagePath);
        File[] files = file.listFiles();
        for (File f : files) {
            if (f.isDirectory()) {
                doScanMappers(rootPath + "." + f.getName());
            } else if (f.getName().endsWith(".class")) {
                String name = f.getName().replaceAll("\\.class", "");
                String className = rootPath + "." + name;
                mapperNames.add(className);
            }
        }
    }


    public static Set<String> getXmlPaths(String rootPath) throws IOException {
        doScanXmls(rootPath);
        return xmlPaths;
    }

    public static Set<String> getMapperNames(String rootPath) throws IOException {
        doScanMappers(rootPath);
        return mapperNames;
    }
}
